<script setup lang="ts">
import {ref, onMounted, computed} from 'vue';
import { type PropType, reactive } from 'vue';
import {BluePrintApi, type ChatType} from '@/views/ai/agent/x6/api/blue-print-api';
import { FilesCard } from 'vue-element-plus-x';
import RulesCheckbox from './components/rulesCheckbox.vue'
import {filter_rule_level, filter_rule_level_type} from "../../../utils/rules";
import {RuleGroupApi} from '@/views/ai/law/api/rulegroup'
import {RuleDetailApi} from '@/views/ai/law/api/ruledetail'
import {messageBus} from "@/views/ai/miuma/chat/hook";
import {ToolsProtocol} from "@/views/ai/miuma/chat/data";
import {TableColumn} from "@/components/ATable/types";
import {useElTableSelector} from "@/components/ATableSelect/f";

const props = defineProps({
  chat: Object as PropType<ChatType>,
});
const form = reactive<any>({});
const rules = ref([] as any);
const getRuleGroupDetail = async (val: any) => {
  const { list } = await RuleDetailApi.getRuleDetailPage({
    groupId: val,
    pageNo: 1,
    pageSize: 100,
  });
  rules.value = list;
};
const doCheck=async (rule:string,fileId:string,onData:(d:any)=>void,onClose:()=>void)=>{
  await BluePrintApi.executeByCode("contract_review_flow",
    {text:`规则内容:${rule}`,fileId},
    (ev)=>{
      try {
        const d=JSON.parse(ev.data)
        onData(d)
      }catch (e){
        console.error(e)
      }
    },
    onClose,
    undefined,
    (e)=>{
      console.error('sendMsgToAi',e)
      throw e
    }
  )
}
interface Task{
  rule:any,
  loading: boolean,
  modify?:string,
  source?:string,
  judgement?:string,
  score?:number,
  selected?:boolean
}
const tasks=ref<Task[]>()
const currentFileId=ref<string>()
const doTask=async ()=>{
  tasks.value=[]
  if (form.checkedRules as [] && props.chat?.props.input.files) {
    const url=props.chat?.props.input.files[0]
    const d=await BluePrintApi.uploadFile2(url,"TongYi")
    currentFileId.value=d.id as string
    checking.value = true
    for (const rule of form.checkedRules) {
      const prom = `请以${form.position}，${form.scale}尺度,${JSON.stringify(rule)}规则进行评判文件中的内容`
      const task = reactive<Task>({rule, loading: true})
      tasks.value.push(task)
      await doCheck(prom, d.id,
        (data: any) => {
          if (data.node === 'VALUE_OUTPUT' && data.status === 'completed') {
            const check = data.data.check
            task.modify = check.modify;
            task.source = check.source;
            task.judgement = check.judgement;
            task.score = check.score;
          }
        },
        () => {
          task.loading = false;
        })
    }
  }
}

const handleSubmit = () => {
  doTask();
};
const reDo=()=>{
  checking.value=false;
}
const checking=ref(false);
const canCheck=computed(()=>{
  return form.type&&form.position&&form.scale&&props.chat?.props?.input?.files&&form.checkedRules?.length>0
})
const canDoTask=computed(()=>{
  return props.chat?.props?.input?.files&&props.chat?.props?.input?.files?.length>0
})
const canWrite=computed(()=>{
  return tasks.value&&tasks.value.filter(i=>i.selected).length>0
})
const colums = reactive<TableColumn[]>([
  {
    label: '分组名称',
    prop: 'name',
    useFilter: true,
    queryForms: [
      {
        label: '筛选',
        component: 'ElInput',
        prop: 'name'
      }
    ]
  }
])
const Selector = useElTableSelector(
  {
    loadFunction:RuleGroupApi.getRuleGroupPage,
    columns:colums,
    selectType:'radio',
    formart:(d:any)=>{
      return d.name
    }
  }
);
const doAutoWrite=()=>{
  const selectTask = tasks.value?.filter(i=>i.selected).map(r=>`规则说明:${r.rule.description},修改建议:${r.judgement},原文修改的内容${r.modify}`);
  const e:ToolsProtocol={
    tools:true,
    component:'DocEditor',
    active:'DoAutoWrite',
    subData:{rules:selectTask,fileId:currentFileId.value}
  }
  console.log("doAutoWrite",e)
  messageBus.emit('useTools',e)
}
const onSelected=async (row:any)=>{
  form.type=row.id
  await getRuleGroupDetail(row.id)
}
</script>

<template>
  <div style="width: 100%">
    <div style="width: 100%" v-if="canDoTask">
      <div v-show="!checking">
        <div style="margin-bottom: 10px; font-weight: bold">
          您好，我们即将对您的文件进行审查!
        </div>
        <el-form label-position="left">
          <el-form-item label="合同类型" >
            <Selector.DOM @selected="onSelected"/>
<!--            <el-select
              v-model="form.type"
              placeholder="请选择文件类型"
              style="width: 240px"
              @change="getRuleGroupDetail"
            >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>-->
          </el-form-item>
          <el-form-item label="审查立场">
            <el-radio-group v-model="form.position">
              <el-radio value="甲方立场">甲方立场</el-radio>
              <el-radio value="乙方立场">乙方立场</el-radio>
              <el-radio value="中立立场">中立立场</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审查尺度">
            <el-radio-group v-model="form.scale">
              <el-radio value="强势">强势</el-radio>
              <el-radio value="弱势">弱势</el-radio>
              <el-radio value="均势">均势</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审查文件">
            <FilesCard v-for="(f,i) in props.chat?.props.input.files" :key="i" :name="f" />
          </el-form-item>
          <el-form-item>
            <div style="max-height: 500px;width: 100%">
              <RulesCheckbox v-model="form.checkedRules" :rules="rules" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button v-show="canCheck" type="primary" style="width: 100%" @click="handleSubmit">开始审查</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="checking">
        <div>
          <div style="display: flex;flex-direction: row;justify-content: right;margin-bottom: 10px">
            <el-button type="primary" @click="reDo">重新进行</el-button>
          </div>
          <div class="task-card" v-for="(task,i) in tasks" :key="i" v-loading="task.loading">
            <el-descriptions :column="1">
              <template #title>
                <div style="flex:1;display: flex; flex-direction: row;flex-wrap: nowrap;gap:5px;overflow: hidden;align-items: center">
                  <el-checkbox v-model="task.selected"/>
                  <el-tag :type="filter_rule_level_type(task.rule.level)">{{filter_rule_level(task.rule.level)}}</el-tag>
                  {{task.rule.name}}
                </div>
              </template>
              <template #extra>
                <div style="font-weight: 700;font-size: 28px;min-width: 50px">{{task.score}}</div>
              </template>
              <el-descriptions-item label="规则说明">
                <div>{{task.rule.description}}</div>
              </el-descriptions-item>
              <el-descriptions-item label="AI意见">
                <div>{{task.judgement}}</div>
              </el-descriptions-item>
              <el-descriptions-item label="修改前">
                <div>{{task.source}}</div>
              </el-descriptions-item>
              <el-descriptions-item label="修改后">
                <div>{{task.modify}}</div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-button type="primary" style="width: 100%" @click="doAutoWrite" :disabled="!canWrite">确认并且自动写作</el-button>
        </div>
      </div>
    </div>
    <div v-else>您必须上传一个文件，我才能帮你进行合同审查!</div>
  </div>
</template>

<style scoped lang="scss">
.task-card{
  background: hsl(var(--background));
  display: flex;
  flex-direction: column;
  padding: 15px;
  border: hsl(var(--border));
  margin-bottom: 10px;
  border-radius: 10px;
}
.task-card:last-child {
  margin-bottom: 0; /* 移除最后一个元素的 margin-bottom */
}
</style>
